import 'package:dio/dio.dart';
import '../common/global.dart';

class CacheObject {
  CacheObject(this.response): timestamp = DateTime.now().millisecondsSinceEpoch;

  Response response;
  int timestamp;

  @override
  bool operator ==(Object other) {
    return response.hashCode == other.hashCode;
  }

  @override
  int get hashCode => response.realUri.hashCode;

  bool isNotExpired(int expired) {
    return (DateTime.now().millisecondsSinceEpoch - timestamp) / 1000 < expired;
  }
}

class NetCache extends Interceptor {
  static var cache = <String, CacheObject>{};
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (!Global.profile.cache!.enable) return handler.next(options);
    bool refresh = options.extra['refresh'] == true;
    if (refresh) {
      cache.remove(options.uri.toString());
      return handler.next(options);
    }
    print(cache);
    if (options.extra['noCache'] != true && options.method.toLowerCase() == 'get') {
      String key = options.extra['cacheKey'] ?? options.uri.toString();
      var objCache = cache[key];
      if (objCache != null) {
        if (objCache.isNotExpired(Global.profile.cache!.expire)) return handler.resolve(objCache.response);
        cache.remove(options.uri.toString());
      }
      handler.next(options);
    }
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (Global.profile.cache!.enable) {
      _cache(response);
    }
    handler.next(response);
  }

  _cache(Response response) {
    RequestOptions options = response.requestOptions;
    if (options.extra['noCache'] != true && options.method.toLowerCase() == 'get') {
      String key = options.extra['cacheKey'] ?? options.uri.toString();
      cache[key] = CacheObject(response);
      print(cache);
    }
  }

}

class HttpUtil {
  static Dio dio = Dio(BaseOptions());

  static void init() {
    dio.interceptors.add(NetCache());
  }
}